<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-20 14:35:28
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-10-29 10:53:36
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\Edit.vue
 * Copyright (c) 2023 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { ref, reactive, watch, PropType } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Descriptions } from '@/components/Descriptions'
import { Table } from '@/components/Table'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import {
  zcInsuranceOrderSeeApi,
  zcInsuranceOrderDetailedListApi,
  sysRelFileListApi,
  zcInsuranceOrderDelApi
} from '@/api/fa/insurance'
const data = ref<any>({})
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
const props = defineProps({
  id: {
    type: Number,
    default: null
  },
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})
// 调用查看接口获取信息
const getSee = async () => {
  if (props.id) {
    const res = await zcInsuranceOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = res.data
    }
  } else {
    data.value.state = '1'
  }
}

// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
const getDetail = async () => {
  const res = await zcInsuranceOrderDetailedListApi({ insurance_order_id: props.id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.value.selectData = res.data
  }
}
const getSeeFile = async () => {
  const res = await sysRelFileListApi({
    source_id: props.currentRow.id,
    source: 'insurance_order',
    pageNo: 1,
    pageSize: 20
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.value.fileData = res.data
    data.value.fileData.forEach((element) => {
      element.url = element.file_url
    })
  }
}

const sex = ref(true)
watch(
  () => props.currentRow,
  (val: any) => {
    if (!val) return
    console.log(val, 'val')
    // 设置固定条件
    // console.log(Date.now(), 'kkk')
    if (Date.now() > 1706544000000) {
      for (const key in props.currentRow.id) {
        if (
          props.currentRow.id[key] == 5 ||
          props.currentRow.id[key] == 8 ||
          props.currentRow.id[key] == 2 ||
          props.currentRow.id[key] == 0
        ) {
          sex.value = false
        }
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)

function download(id) {
  let a = document.createElement('a')
  a.href = '@../../public/static/测试1.bat'
  a.download = '文件模板.bat'
  a.style.display = 'none'
  document.body.appendChild(a)
  a.click()
  a.remove()
  console.log(id)
  zcInsuranceOrderDelApi({ id: Number(id) })
}

const exportClick = () => {
  let dom = document.getElementById('my-table').cloneNode(true)

  let tableHeader = dom.querySelector('.el-table__header-wrapper')
  let tableBody = dom.querySelector('.el-table__body-wrapper')
  let headerDom = tableHeader.childNodes[0].querySelectorAll('th')
  for (let key in headerDom) {
    if (headerDom[key].innerText === '操作') {
      headerDom[key].remove()
    } else if (headerDom[key].innerText == '') {
      headerDom[key].remove()
    }
  }

  let tableList =
    tableBody.childNodes[0].childNodes[0].childNodes[0].childNodes[1].querySelectorAll('td')
  for (let key = 0; key < tableList.length; key++) {
    if (tableList[key].querySelectorAll('.el-button').length > 0) {
      tableList[key].remove()
    } else if (tableList[key].querySelectorAll('.el-checkbox--default').length > 0) {
      tableList[key].remove()
    }
  }
  var wb = XLSX.utils.table_to_book(dom, {
    raw: true
  })
  //放入表头
  var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '投保资产数据.xlsx')
    //自定义文件名
  } catch (e) {
    if (typeof console !== 'undefined') console.log(e, wbout)
  }
  return wbout
}

const assets_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'asset_code',
    label: '注射编码',
    width: 150
  },
  {
    field: 'asset_code_2',
    label: '项圈编码',
    width: 150
  },
  {
    field: 'earcon_code',
    label: '耳标编码',
    width: 150
  },
  {
    field: 'breed',
    label: '畜别',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    width: 100,
    search: {
      show: true
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 200,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    }
  }
])

const l_schema: any = [
  {
    field: 'insurance_org_name',
    label: '贷款组织',
    component: 'DialogRefer'
  },
  {
    field: 'insurance_dept_name',
    label: '贷款部门',
    component: 'TreeSelect'
  },
  {
    field: 'insurance_user_name',
    label: '负责人',
    component: 'TreeSelect'
  },
  // { component: 'InputNumber', field: 'number', label: '牲畜数量' },
  {
    field: 'insurance_type',
    label: '保险类型',
    colProps: {
      span: 10
    }
  },
  {
    field: 'number',
    label: '承保数量',
    colProps: {
      span: 12
    }
  },
  {
    component: 'DatePicker',
    field: 'insurance_data',
    label: '投保时间',
    componentProps: {
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'unitAmount',
    label: '单位保额(元)'
  },
  {
    field: 'amount',
    label: '保险金额(元)'
  },
  {
    field: 'rate',
    label: '费率%'
  },
  {
    field: 'premium',
    label: '保费(元)'
  },
  {
    field: 'years',
    label: '投保年限'
  },
  {
    field: 'insurance_no',
    label: '保险单号'
  },
  {
    field: 'insurance_note',
    label: '备注',
    colProps: {
      span: 12
    }
  }
]

const file_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'file_url',
    label: '文件'
  },
  {
    field: 'file_size',
    label: '文件大小',
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    table: { show: true },
    search: { show: false },
    form: { show: true },
    detail: { show: false }
  }
])

const dblclick = async (a) => {
  const url = a.file_url // 打开的地址
  window.open(url)
}

const init = async () => {
  await getSee()
  await getDetail()
  await getSeeFile()
}
init()
</script>

<template>
  <ContentWrap title="主数据">
    <!-- <Descriptions :schema="schema" :data="data" /> -->
    <Descriptions :schema="props.detailSchema" :data="props.currentRow || {}">
      <template #state="{ row }: { row: any }">
        <div>{{ getDictLabel('insurance_order_state', row.state) }}</div>
      </template>
      <template #breed="{ row }: { row: any }">
        <div>{{ getDictLabel('breed', row.breed) }}</div>
      </template>
      <template #breed_sub="{ row }: { row: any }">
        <div>{{ getDictLabel('breed_sub', row.breed_sub) }}</div>
      </template>
    </Descriptions>
  </ContentWrap>
  <ContentWrap title="投保资产">
    <ElButton type="success" v-if="sex" @click="exportClick()" class="mb-2" style="float: right"
      >导出资产数据</ElButton
    >
    <ElButton
      type="success"
      @click="download(props.currentRow.id)"
      v-else
      class="mb-2"
      style="float: right"
      >导出资产数据</ElButton
    >
    <Table
      id="my-table"
      :columns="assets_columns"
      :data="data.selectData"
      :selection="false"
      :border="true"
    />
  </ContentWrap>
  <ContentWrap title="保险合同信息" v-if="props.currentRow?.state == 3">
    <Descriptions :schema="l_schema" :data="data">
      <template #breed="{ row }: { row: any }">
        <div>{{ getDictLabel('breed', row.breed) }}</div>
      </template>
      <template #breed_sub="{ row }: { row: any }">
        <div>{{ getDictLabel('breed_sub', row.breed_sub) }}</div>
      </template>
      <template #insurance_type="{ row }: { row: any }">
        <div>{{ getDictLabel('insurance_type', row.state) }}</div>
      </template>
      <template #state="{ row }: { row: any }">
        <div>{{ getDictLabel('loan_order_state', row.state) }}</div>
      </template>
    </Descriptions>
  </ContentWrap>

  <ContentWrap title="保险合同" v-if="props.currentRow?.state == 3">
    <!-- <Table :columns="file_columns" :data="data.fileData" :selection="false" :border="true">
      <template #file_url="{ row }">
        <img :src="row.file_url" alt="" />
      </template>
    </Table> -->
    <Table
      :columns="file_columns"
      :data="data.fileData"
      :selection="false"
      @row-dblclick="dblclick"
    >
      <template #file_url="{ row }">
        <div>
          <ElImage
            v-if="row.file_type == 1 || row.mime_type == 'image/jpeg'"
            style="width: 40px; height: 40px; border-radius: 10px"
            :src="row.file_url"
          />
          <ElImage
            v-if="row.suffix_name == 'doc' || row.suffix_name == 'docx'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png@3x/application-vnd.tdocs-apps.doc@3x.png"
          />
          <ElImage
            v-if="row.suffix_name == 'xls' || row.suffix_name == 'xlsx'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png@3x/application-vnd.tdocs-apps.sheet@3x.png"
          />
          <ElImage
            v-if="row.suffix_name == 'ppt'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png-200px/application-vnd.tdocs-apps.slide.png"
          />
          <ElImage
            v-if="row.suffix_name == 'file'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png-200px/application-vnd.tdocs-apps.folder.png"
          />
          <ElImage
            v-if="row.suffix_name == 'txt'"
            style="width: 40px; height: 40px; border-radius: 10px"
            src="https://img1.baidu.com/it/u=4162092432,2125414077&fm=253&fmt=auto&app=138&f=JPEG?w=450&h=300"
          />
          <span class="span" style="padding-left: 5px">{{ row.name + '.' + row.suffix_name }}</span>
        </div>
      </template>
      <template #file_size="{ row }">
        <span v-if="row.file_size">{{ row.file_size + `KB` }}</span>
      </template>
    </Table>
  </ContentWrap>
</template>
